/*
 * ComerciosBusquedaFrame.java
 *
 * Created on 16 de abril de 2008, 11:45 PM
 */
package org.vehiculos.placas;

import org.mybeans.Sesion;
  
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author  avbravo
 */
public class VehiculosPlacasPagadosFrame extends javax.swing.JFrame {

    Sesion sesion;
    int fila = -1;
    DefaultTableModel modelo;
    int Contador = 0;
    String MesPago;
    int Anio;

    /** Creates new form ComerciosBusquedaFrame */
    public VehiculosPlacasPagadosFrame() {
        initComponents();
        sesion = new Sesion();


        /*
         * Fondo
         */

        
          
         

         
         

        /*
         * fin del fondo
         */
        AutoCompleteDecorator.decorate(this.jComboBoxMesPago);
        jTextFieldTotal.setText("");
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        this.Anio = ca.get(java.util.Calendar.YEAR);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButtonRegresar = new javax.swing.JButton();
        jButtonRegresar2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxMesPago = new javax.swing.JComboBox();
        jButtonConsultar = new javax.swing.JButton();
        jButtonImprimir = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldTotal = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("PLACAS VENDIDAS POR MES");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setOpaque(false);

        jButtonRegresar.setMnemonic('r');
        jButtonRegresar.setText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jButtonRegresar2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar2.setToolTipText("Regresar");
        jButtonRegresar2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresar2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Mes");

        jComboBoxMesPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" }));
        jComboBoxMesPago.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxMesPagoActionPerformed(evt);
            }
        });

        jButtonConsultar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/consultar.png"))); // NOI18N
        jButtonConsultar.setToolTipText("Consultar");
        jButtonConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConsultarActionPerformed(evt);
            }
        });

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/print.jpeg"))); // NOI18N
        jButtonImprimir.setToolTipText("Imprimir");
        jButtonImprimir.setEnabled(false);
        jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirActionPerformed(evt);
            }
        });

        jLabel2.setText("Total");

        jTextFieldTotal.setEditable(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(169, 169, 169)
                        .addComponent(jButtonRegresar))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(60, 60, 60)
                        .addComponent(jComboBoxMesPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonRegresar2)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxMesPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonConsultar)
                    .addComponent(jButtonRegresar2)
                    .addComponent(jButtonImprimir)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(184, 184, 184)
                .addComponent(jButtonRegresar)
                .addContainerGap())
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "placa", "id", "dueño", "telefono"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed

    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonRegresar2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresar2ActionPerformed
    // TODO add your handling code here:
    dispose();
}//GEN-LAST:event_jButtonRegresar2ActionPerformed

private void jComboBoxMesPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxMesPagoActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jComboBoxMesPagoActionPerformed

private void jButtonConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConsultarActionPerformed
    // TODO add your handling code here:
    try {

        MesPago = (String) this.jComboBoxMesPago.getSelectedItem();

        if (MesPago == null || MesPago.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione el mes de pago", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        modelo = new DefaultTableModel();
        // Creamos las columnas.
        modelo.addColumn("placa");
        modelo.addColumn("id");
        modelo.addColumn("dueno");
        modelo.addColumn("telefono");
        sesion.LimpiarTemporales();
        this.Contador = 0;
        String sql = "select vehicles.idvehiculo,vehicles.placa, contribuyentes.cedula as id, contribuyentes.contribuyente as dueno, contribuyentes.telefono from vehicles , contribuyentes, vehiclespagosplacas where vehicles.idmunicipio ='" + sesion.getIdmunicipio() + "' and vehicles.mespago='" + MesPago + "' and  vehicles.activo ='si' and vehicles.tipoid ='contribuyentes' and contribuyentes.idmunicipio = vehicles.idmunicipio and contribuyentes.activo = 'si' and contribuyentes.cedula = vehicles.id and vehiclespagosplacas.idmunicipio = vehicles.idmunicipio and vehiclespagosplacas.idvehiculo = vehicles.idvehiculo and vehiclespagosplacas.anio ='"+ this.Anio+"' and vehiclespagosplacas.activo='si'";
        CargarTodosRegistros(sql);

        sql = "select vehicles.idvehiculo,vehicles.placa, comercios.ruc as id, comercios.comercio as dueno, comercios.telefono from vehicles , comercios, vehiclespagosplacas where vehicles.idmunicipio ='" + sesion.getIdmunicipio() + "' and vehicles.mespago='" + MesPago + "' and  vehicles.activo ='si' and vehicles.tipoid ='comercios' and comercios.idmunicipio = vehicles.idmunicipio and comercios.activo = 'si' and comercios.idcomercio = vehicles.id  and vehiclespagosplacas.idmunicipio = vehicles.idmunicipio and vehiclespagosplacas.idvehiculo = vehicles.idvehiculo and vehiclespagosplacas.anio ='"+ this.Anio+"' and vehiclespagosplacas.activo='si'";
        CargarTodosRegistros(sql);
        jTextFieldTotal.setText(String.valueOf(this.Contador));
        jButtonImprimir.setEnabled(true);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Boton Consultar()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_jButtonConsultarActionPerformed

private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed
    // TODO add your handling code here:
    try {
        String STotal = jTextFieldTotal.getText();
        if (STotal == null || STotal.equals("") || STotal.equals("0.0")) {
            JOptionPane.showMessageDialog(this, "No existen recibos en las fechas indicadas", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String reportSource;
        String reportDest;
        String sql;

        // reportSource = sesion.getRutaReportes() + "ContabilidadInformeIngresos.jrxml";
        reportSource = sesion.getRutaReportes() + "VehiculosPlacas.jrxml";

      
        Map<String, Object> params = new HashMap<String, Object>();


        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        JasperReport jasperReport =
                JasperCompileManager.compileReport(reportSource);
        params.put("P_IDMUNICIPIO", sesion.getIdmunicipio());
        params.put("P_MUNICIPIO", sesion.getMunicipio());
        params.put("P_NOMBREUSUARIO", sesion.getUsuario());
        params.put("P_USERNAME", sesion.getUsername());
        params.put("P_CONDICION","PLACAS VENDIDAS DEL MES " + this.MesPago);

        params.put("P_TOTAL", String.valueOf(this.Contador));


        JasperPrint jasperPrint =
                JasperFillManager.fillReport(
                jasperReport, params, sesion.con);
        JasperViewer.viewReport(jasperPrint, false);

    } catch (JRException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

}//GEN-LAST:event_jButtonImprimirActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new VehiculosPlacasPagadosFrame().setVisible(true);
            }
        });
    }

    public void CargarTodosRegistros(String sql) {
        try {

            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            PreparedStatement psquery = sesion.con.prepareStatement(sql);
            ResultSet rs = psquery.executeQuery();



// Bucle para cada resultado en la consulta
            while (rs.next()) {
                this.Contador++;
                // Se crea un array que será una de las filas de la tabla.
                Object[] fila = new Object[4]; // Hay tres columnas en la tabla
                String placa = rs.getString("placa");
                if (placa == null) {
                    placa = "";
                }
                String id = rs.getString("id");
                if (id == null) {
                    id = "";
                }
                String dueno = rs.getString("dueno");
                if (dueno == null) {
                    dueno = "";
                }
                String telefono = rs.getString("telefono");
                if (telefono == null) {
                    telefono = "";
                }
                fila[0] = placa;
                fila[1] = id;
                fila[2] = dueno;
                fila[3] = telefono;

                modelo.addRow(fila);
                String sqlInsert = "INSERT into temporalvehiculosplacas (placa,id,propietario,telefono,idmunicipio,username)  VALUES(?,?,?,?,?,?)";
                PreparedStatement prestInsert = sesion.con.prepareStatement(sqlInsert);
                prestInsert.setString(1, placa);
                prestInsert.setString(2, id);
                prestInsert.setString(3, dueno);
                prestInsert.setString(4, telefono);
                prestInsert.setString(5, sesion.getIdmunicipio());
                prestInsert.setString(6, sesion.getUsername());
                prestInsert.executeUpdate();

            }
            this.jTable1.setModel(modelo);
            jTable1.setVisible(true);
            //aris++
            this.jTable1.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {

                    fila = jTable1.rowAtPoint(e.getPoint());
                    int columna = jTable1.columnAtPoint(e.getPoint());
                    if ((fila > -1) && (columna > -1)) {
//                        jTextFieldIdVehiculo.setText(String.valueOf(jTable1.getValueAt(fila, 0)));
                        //                      jTextFieldPlaca.setText(String.valueOf(jTable1.getValueAt(fila, 1)));
                        //       CargarVehiculos();
                    }
                }
            });

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "CargarTodosRegistros()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonConsultar;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JButton jButtonRegresar2;
    private javax.swing.JComboBox jComboBoxMesPago;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldTotal;
    // End of variables declaration//GEN-END:variables
}
